const sequelize = require('sequelize')
const Questionnaire = require('../db/model/Questionnaire')
const dbhelper = require('../db/helper')

async function saveQuestionnaire ({type, group, unit, answers, questuser}) {
  await dbhelper.updateOrCreate(Questionnaire,
    {[sequelize.Op.and]: [{typeid: type, groupid: group, unitid: unit}]},
    {typeid: type, groupid: group, unitid: unit, answerscontent: answers, questuser: questuser})

  return getQuestionnaire({type, group, unit})
}

async function getQuestionnaire ({type, group, unit}) {
  const questionnaire = await Questionnaire.findOne({
    where: {[sequelize.Op.and]: [{typeid: type, groupid: group, unitid: unit}]},
    order: [
      ['id', 'desc']
    ]
  })
  return (questionnaire === null) ? [] : questionnaire.dataValues
}

module.exports = {
  saveQuestionnaire,
  getQuestionnaire
}
